package com.ebt.m.customer.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.ebt.m.AppInitService;
import com.ebt.m.R;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.commons.widgets.BaseRxFragment;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.entity.CustomerBatchDelete;
import com.ebt.m.customer.entity.CustomerDelete;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.event.EventMultiChooseAll;
import com.ebt.m.customer.event.EventMultiChooseDelete;
import com.ebt.m.customer.event.EventMultiChooseIsAll;
import com.ebt.m.customer.event.EventMultiChooseOff;
import com.ebt.m.customer.event.EventMultiChooseOn;
import com.ebt.m.customer.event.EventMultiChooseUpdateCount;
import com.ebt.m.customer.model.CustomerModelNew;
import com.ebt.m.customer.net.json.CustomerCRUDRetJson;
import com.ebt.m.customer.util.MultiChooseManager;
import com.ebt.m.customer.util.ToastUtil;
import com.ebt.m.customer.view.CustomerMainContentView;
import com.ebt.m.customer.view.VerticalStraightTextView2;
import com.ebt.m.data.CustomerData;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.utils.SharedElementUtil;
import com.google.gson.Gson;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 客户主界面
 */
public class FragmentCustomerMain extends BaseRxFragment {

    private static final String TAG = FragmentCustomerMain.class.getSimpleName();

    private static final int REQUEST_CODE_PICK_FILE = 1003;
    private static final int REQUEST_CODE_CAMERA = 1004;
    private static final int REQUEST_CODE_CAPTURE = 1005;

    public static final ArrayList<Integer> REQUEST_CODES = new ArrayList<>();

    static {
        REQUEST_CODES.add(REQUEST_CODE_PICK_FILE);
        REQUEST_CODES.add(REQUEST_CODE_CAMERA);
        REQUEST_CODES.add(REQUEST_CODE_CAPTURE);
    }

    //views
    private View mContentView;
    private View mSearchView;
    private TextView mToastView;
    private CustomerMainContentView mMainView;
    private VerticalStraightTextView2 mAlphabetView;
    private View multi_select_bottom;
    private View multi_select_top;
    private TextView multi_select_cancel;
    private TextView multi_select_all;
    private TextView multi_select_count;
    private TextView tv_multi_edit;

    private DialogWaitProgress waitDialog = null;

    private void showWaitProgressDialog() {
        if (waitDialog == null) {
            waitDialog = new DialogWaitProgress(this.getContext());
            waitDialog.setTextMessage("正在删除客户...");
        }
        if (waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
        waitDialog.show();
    }

    private void dismissWaitProgressDialog() {
        if (waitDialog == null) {
            waitDialog = new DialogWaitProgress(this.getContext());
        }
        if (waitDialog.isShowing()) {
            waitDialog.dismiss();
        }
    }

    //data
    private HashMap<Integer, Integer> mSectionToPosition = new HashMap();
    private List<CustomerModelNew> mCustomerModelNews;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    public static FragmentCustomerMain newInstance() {
        Bundle bundle = new Bundle();
        FragmentCustomerMain fragmentCustomerMain = new FragmentCustomerMain();
        fragmentCustomerMain.setArguments(bundle);
        return fragmentCustomerMain;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_customer_main, null);
        initViews();
        initViewData();
        return mContentView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initDelay();
    }

    private void initViews() {
        mMainView = (CustomerMainContentView) mContentView.findViewById(R.id.content);
        mMainView.setBaseRxFragment(this);
        mAlphabetView = (VerticalStraightTextView2) mContentView.findViewById(R.id.fragment_customer_import_v_alphabet);
        mToastView = (TextView) mContentView.findViewById(R.id.fragment_customer_import_tv_toast);
        mSearchView = mContentView.findViewById(R.id.search);
        mToastViewHeight = mToastView.getLayoutParams().height;
        multi_select_bottom = mContentView.findViewById(R.id.multi_select_bottom);
        multi_select_top = mContentView.findViewById(R.id.multi_select_top);
        multi_select_cancel = (TextView) mContentView.findViewById(R.id.multi_select_cancel);
        multi_select_all = (TextView) mContentView.findViewById(R.id.multi_select_all);
        multi_select_count = (TextView) mContentView.findViewById(R.id.multi_select_count);
        tv_multi_edit = (TextView) mContentView.findViewById(R.id.tv_multi_edit);

        RxView.clicks(multi_select_cancel)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    EventBus.getDefault().post(new EventMultiChooseOff());
                });
        RxView.clicks(multi_select_all)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    selectAll();
                });
        RxView.clicks(multi_select_bottom)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    deleteSelectCustomers();
                });
        RxView.clicks(tv_multi_edit)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    toggleMultiMode();
                    refreshMultiEditText();
                });
        RxView.clicks(mSearchView)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    Intent intent = new Intent(getContext(), ActivityCustomerSearch.class);
                    startActivity(intent);
                    ((Activity) getContext()).overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                });
        refreshMultiEditText();

    }

    private void initViewData() {
        mMainView.update(new CustomerMainContentView.UpdateListener() {
            @Override
            public void onUpdateFinish(List<CustomerModelNew> customerModelNews) {
                if (mSectionToPosition != null) {
                    mSectionToPosition.clear();
                }
                mCustomerModelNews = customerModelNews;
                if (customerModelNews == null || customerModelNews.size() == 0) {
                    setAlphabetListener(false);
                } else {
                    setAlphabetListener(true);
                }
            }

            @Override
            public void onUpdateStart() {
            }

            @Override
            public void onUpdateError() {
                setAlphabetListener(false);
            }
        });
    }

    private void initDelay() {
        getView().post(new Runnable() {
            @Override
            public void run() {
                mToastParentViewHeight = ((View) (mToastView.getParent())).getMeasuredHeight();
            }
        });
    }

    private int mToastViewHeight;
    private int mToastParentViewHeight;

    private void setAlphabetListener(boolean hasData) {
        if (hasData) {
            mAlphabetView.setOnTouchedCharListener(new VerticalStraightTextView2.OnTouchedCharListener() {

                @Override
                public void onTouchedCharReleased(String releasedString, int releasedIndex) {
                }

                @Override
                public void onTouchedCharChanged(String releasedString, int releasedIndex, String pickedString, int pickedIndex) {
                }

                @Override
                public void onTouchedCharPicked(String pickedString, int pickedIndex) {
                    String sectionLetterActionDown = String.valueOf(CustomerConstant.Sort.CHARS_ALPHA[pickedIndex]);
                    mToastView.setText(sectionLetterActionDown);
                    mToastView.setVisibility(View.VISIBLE);
                    int positionActionDown = getPositionForSection(pickedIndex);
                    mMainView.setSelection(positionActionDown + CustomerMainContentView.PRE_EXTRA_SIZE);
                }

                @Override
                public void onTouchedCharReleasedFinally(String releasedString, int releasedIndex) {
                    mToastView.setVisibility(View.GONE);
                }

                @Override
                public void onTouchedY(float y) {
                    if (y < mToastViewHeight / 2) {
                        mToastView.setTranslationY(-(mToastParentViewHeight - mToastViewHeight) / 2);
                        return;
                    }
                    if (y > mToastParentViewHeight - mToastViewHeight / 2) {
                        mToastView.setTranslationY((mToastParentViewHeight - mToastViewHeight) / 2);
                        return;
                    }
                    mToastView.setTranslationY(y - mToastParentViewHeight / 2);
                }
            });

            if (mAlphabetView.getVisibility() != View.VISIBLE) {
                mAlphabetView.setVisibility(View.VISIBLE);
            }
        } else {
            mAlphabetView.setOnTouchedCharListener(null);
            if (mAlphabetView.getVisibility() != View.GONE) {
                mAlphabetView.setVisibility(View.GONE);
            }
        }
    }


    private void refreshMultiEditText() {
        if (MultiChooseManager.getInstance().getInMultiChooseMode()) {
            tv_multi_edit.setText("取消");
        } else {
            tv_multi_edit.setText("编辑");
        }
    }

    private void toggleMultiMode() {
        if (MultiChooseManager.getInstance().getInMultiChooseMode()) {
            //关闭多选模式
            MultiChooseManager.getInstance().setInMultiChooseMode(false);
            EventBus.getDefault().post(new EventMultiChooseOff());
        } else {
            //打开多选模式
            MultiChooseManager.getInstance().setInMultiChooseMode(true);
            MultiChooseManager.getInstance().clearFlags();
            EventBus.getDefault().post(new EventMultiChooseOn());
        }
    }

    private void selectAll() {
        EventBus.getDefault().post(new EventMultiChooseAll());
        MultiChooseManager.getInstance().selectAll();
        EventBus.getDefault().post(new EventMultiChooseUpdateCount());
    }

    private void deleteSelectCustomers() {
        if (!NetUtils.isNetworkAvailable(getContext())) {
            ToastUtil.showToast(getString(R.string.network_fail));
            return;
        }
        List<Object> list = MultiChooseManager.getInstance().getSelectedObjects();
        if (list != null) {
            List<CustomerDelete> customerDeletes = new ArrayList<>();
            for (Object item : list) {
                customerDeletes.add(new CustomerDelete((String) item));
            }

            Gson gson = new Gson();
            String body = gson.toJson(customerDeletes);
            CustomerBatchDelete entity = new CustomerBatchDelete();
            entity.setCustomerBatchDelete(body);
            showWaitProgressDialog();
            EBTAPI ebtapi = AppInitService.getEbtApi();
            ebtapi.deleteBatchCustomer(entity).compose(RxUtil.rxTransformer(this)).subscribe(getCustomerDeleteSubscriber());
        } else {
            ToastUtil.showToast("请选则客户");
        }
    }

    private Observer getCustomerDeleteSubscriber() {
        return new Observer<CustomerCRUDRetJson>() {

            @Override
            public void onComplete() {
                dismissWaitProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissWaitProgressDialog();
                ToastUtil.showToast("客户批量删除失败" + e.getMessage());
            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(CustomerCRUDRetJson customerCreateRetJson) {
                dismissWaitProgressDialog();
                if (customerCreateRetJson == null) {
                    ToastUtil.showToast("客户批量删除失败");
                    return;
                }
                if (customerCreateRetJson.error != null) {
                    ToastUtil.showToast("客户批量删除失败 \n" + "出错代码为:"
                            + customerCreateRetJson.error.message);
                    return;
                }
                if (customerCreateRetJson.error == null) {
                    if (customerCreateRetJson.data == null) {
                        ToastUtil.showToast("客户批量删除失败");
                        return;
                    } else {
                        CustomerData cd = new CustomerData(getContext());
                        cd.deleteCustomerFromContact(customerCreateRetJson.data.customerBatchDelete);
                        ToastUtil.showToast("客户批量删除成功");
                        EventBus.getDefault().post(new EventMultiChooseOff());
                        EventBus.getDefault().post(new EventCustomerListRefresh());
                    }
                }
            }
        };
    }

    private void refreshSectionToPosition() {
        if (mSectionToPosition == null) {
            mSectionToPosition = new HashMap<>();
        } else {
            mSectionToPosition.clear();
        }
    }

    public int getPositionForSection(int currSection) {
        if (currSection >= CustomerConstant.Sort.CHARS_ALPHA_SIZE) {
            return -1;
        }
        Integer p = mSectionToPosition.get(currSection);
        if (p != null) {
            return p;
        }
        int lastSection = currSection;
        int from = 0;
        while (!mSectionToPosition.containsKey(--lastSection) && lastSection >= 0) {
        }

        if (lastSection >= 0) {
            from = mSectionToPosition.get(lastSection);
        }

        char c = CustomerConstant.Sort.CHARS_ALPHA[currSection];

        int size = mCustomerModelNews.size();
        for (int i = from; i < size; i++) {
            if (mCustomerModelNews.get(i).sortKeyChar.charAt(0) >= c) {
                mSectionToPosition.put(currSection, i);
                return i;
            }
        }
        return -1;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSectionToPosition != null) {
            mSectionToPosition.clear();
        }
        EventBus.getDefault().unregister(this);
        SharedElementUtil.setExitSharedElementCallback(getActivity(), null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCustomerListRefresh event) {
        if (mMainView != null) {
            initViewData();
        }
        refreshSectionToPosition();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseOff event) {
        MultiChooseManager.getInstance().clearFlags();
        MultiChooseManager.getInstance().setInMultiChooseMode(false);
//        multi_select_top.setVisibility(View.GONE);
//        multi_select_bottom.setVisibility(View.GONE);
        refreshMultiEditText();
        onEventMainThread(new EventMultiChooseUpdateCount());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseDelete event) {
        deleteSelectCustomers();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseOn event) {
        MultiChooseManager.getInstance().clearFlags();
        MultiChooseManager.getInstance().setInMultiChooseMode(true);
//        multi_select_top.setVisibility(View.VISIBLE);
//        multi_select_bottom.setVisibility(View.VISIBLE);
        refreshMultiEditText();
        onEventMainThread(new EventMultiChooseUpdateCount());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseUpdateCount event) {
        int selected = MultiChooseManager.getInstance().getSelectedObjects().size();
        multi_select_count.setText("已选择" + selected + "个");
        int all = MultiChooseManager.getInstance().getAllSize();
        if (selected == all && all > 0) {
            EventBus.getDefault().post(new EventMultiChooseIsAll(true));
        } else if (selected < all && all >= 0) {
            EventBus.getDefault().post(new EventMultiChooseIsAll(false));
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        onEventMainThread(new EventMultiChooseOff());
    }
}